package de.firefligher.network.ice.messenger.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;

public class ChatServer implements Runnable, EventSender {
	public static void main(String[] args) {
		Thread thread = new Thread(new ChatServer());
		thread.start();
	}

	private ServerSocket listen;
	private Vector<Connection> connections;
	
	public ChatServer() {
		try {
			listen = new ServerSocket(4048);
		} catch (IOException e) {
			System.err.println("[Error]: Port already in use! Maybe you started two ChatServer!");
			System.exit(1);
		}
		
		connections = new Vector<Connection>();
	}
	
	@Override
	public void run() {
		while(true) {
			try {
				Socket client = listen.accept();
				
				Connection c = new Connection(this, client);
				connections.addElement(c);
			} catch (IOException e) {
				System.err.println("[Error]: Coudn't accept connection!");
				System.exit(1);
			}
		}
	}

	@Override
	public void sendMessage(String par1String) {
		System.out.println(par1String);
	}

	@Override
	public String getInvName() {
		return "ChatServer";
	}

	public void sendMessageToAll(String message) {
		for(int i = 0; i < connections.size(); i++) {
			Connection conn = connections.elementAt(i);
			conn.out.println(message);
		}
	}
}
